var websocket;

function initWebsocket() {
    output = document.getElementById("output");

    var wsUri = getRootUri() + "/webshooter/echo";
    websocket = new WebSocket(wsUri);
    websocket.onopen = function() {
        onOpen();
    };
    websocket.onmessage = function(evt) {
        onMessage(evt);
    };
    websocket.onerror = function(evt) {
        onError(evt);
    };
}

function getRootUri() {
    return "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" +
            (document.location.port === "" ? "8080" : document.location.port);
}

function onOpen() {
}

function onMessage(evt) {
    var obj = JSON.parse(evt.data);
    var events = obj.events;

    for (var i = 0; i < events.length; i++) {
        var event = events[i];
        if (event.type === "CREATE_ENTITY_EVENT") {
            updateEntity(event);
        } else if (event.type === "UPDATE_ENTITY_EVENT") {
            updateEntity(event);
        } else if (event.type === "REMOVE_ENTITY_EVENT") {
            removeEntity(event);
        } else if (event.type === "SHOOT_EFFECT") {
            addShootEffect(event);
            startShootAnimation(event);
        }
    }
}

function joinGame() {
    var joinMsg = {};
    joinMsg.type = "JOIN_COMMAND";

    send(joinMsg);
}

function keydown(keyCode) {
    var msg = {};

    msg.type = "KEY_DOWN_COMMAND";
    msg.keyCode = keyCode;

    send(msg);
}

function keyup(keyCode) {
    var msg = {};

    msg.type = "KEY_UP_COMMAND";
    msg.keyCode = keyCode;

    send(msg);
}

function mousedown(mouseButton, angle) {
    var msg = {};

    msg.type = "MOUSE_DOWN_COMMAND";
    msg.mouseButton = mouseButton;
    msg.angle = angle;

    send(msg);
}

function mouseup(mouseButton) {
    var msg = {};

    msg.type = "MOUSE_UP_COMMAND";
    msg.mouseButton = mouseButton;

    send(msg);
}

function updatePlayerAngle(angle) {
    var msg = {};

    msg.type = "UPDATE_PLAYER_ANGLE_COMMAND";
    msg.angle = angle;

    send(msg);
}

function send(msg) {
    msg.name = playerId.value;
    var jsonstr = JSON.stringify(msg);
    websocket.send(jsonstr);
}